import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/widgets/gt_button_v3.dart';
import 'package:lib_uikit/widgets/gt_checkbox_v3.dart';
import 'package:lib_uikit/widgets/text/gt_text.dart';

class GTPopupWidgetV3 extends StatefulWidget {
  final String? title;
  final Widget? contentView;
  final String? startButtonText;
  final String? endButtonText;
  final VoidCallback? onConfirmClick;
  final VoidCallback? onCancelClick;
  final VoidCallback? closeClick;
  final bool? onlyExpandConfirm;
  final ValueChanged<double>? heightCallBack;
  final Widget? bottomWidget;

  //Android-miniapp工程专用
  //工程内部一些配置会导致吞掉一部分的下间距，所以需要额外添加下间距
  final bool? isMiniapp;

  const GTPopupWidgetV3({
    super.key,
    this.title,
    this.contentView,
    this.startButtonText,
    this.endButtonText,
    this.onConfirmClick,
    this.onCancelClick,
    this.onlyExpandConfirm,
    this.heightCallBack,
    this.bottomWidget,
    this.closeClick,
    this.isMiniapp,
  });

  @override
  State<StatefulWidget> createState() => _PopupStateV3();
}

class _PopupStateV3 extends State<GTPopupWidgetV3> {
  double screenMaxPercent = 0.8;
  final GlobalKey _widgetKey = GlobalKey();
  bool _isMiniApp = false;

  @override
  void initState() {
    super.initState();
    _isMiniApp = (widget.isMiniapp ?? false) && Platform.isAndroid;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getWidgetHeight();
    });
  }

  void _getWidgetHeight() {
    final RenderBox renderBox = _widgetKey.currentContext?.findRenderObject() as RenderBox;
    double theHeight = renderBox.size.height;
    widget.heightCallBack?.call(theHeight);
  }

  @override
  Widget build(BuildContext context) {
    //屏幕高度
    double screenHeight = GTScreen.getHeight(context) - GTScreen.getTopSafeHeight(context);
    //弹窗最大高度
    double bottomSheetMaxHeight = screenHeight * screenMaxPercent;
    //弹窗最小高度
    double bottomSheetMinHeight = screenHeight * 0.4;
    double cancelHeight = 72 + View.of(context).padding.bottom;
    if (_isMiniApp) {
      cancelHeight += 8;
    }
    double titleHeight = 59;
    // child的最大高度：总的最大高度-标题高度-cancel高度
    double childMaxHeight = bottomSheetMaxHeight - titleHeight - cancelHeight;
    double childMinHeight = bottomSheetMinHeight - titleHeight - cancelHeight;

    String _startButtonText = widget.startButtonText ?? "";
    String _endButtonText = widget.endButtonText ?? "";
    return GestureDetector(
      onVerticalDragUpdate: (details) {
        double dy = details.primaryDelta ?? 0;
        if (dy < 0) {
          //向上滑动
          setState(() {
            screenMaxPercent = 1;
          });
        }
      },
      child: Container(
        key: _widgetKey,
        constraints: BoxConstraints(
          minHeight: bottomSheetMinHeight,
          maxHeight: bottomSheetMaxHeight,
        ),
        decoration: BoxDecoration(
          color: GTColorsV3.cmpt16.color,
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
          ),
        ),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Container(
                      height: 51,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Flexible(
                            child: GTText(
                              removeTopBottomPadding: true,
                              widget.title ?? "",
                              softWrap: true,
                              style: gtTextStyleW700(fontSize: 16, color: GTColorsV3.text1.color),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      widget.closeClick?.call();
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Icon(
                        GTIconFont.e89b,
                        size: 16,
                        color: GTColorsV3.icon3.color,
                      ),
                    ),
                  ),
                ],
              ),
              if (widget.contentView != null) ...[
                Container(
                  constraints: BoxConstraints(maxHeight: childMaxHeight, minHeight: childMinHeight),
                  child: NotificationListener<UserScrollNotification>(
                    onNotification: (notification) {
                      // 滑动开始时判断滑动方向
                      if (notification.direction == ScrollDirection.forward) {
                        // 向下滑动，允许内部滑动布局处理滑动事件
                        return false;
                      } else if (notification.direction == ScrollDirection.reverse) {
                        // 向上滑动，触发外部GestureDetector的滑动事件
                        setState(() {
                          screenMaxPercent = 1;
                        });
                        // 阻止内部滑动布局处理滑动事件
                        return true;
                      }
                      return false;
                    },
                    child: widget.contentView!,
                  ),
                ),
              ],
              if (_startButtonText.isNotEmpty || _endButtonText.isNotEmpty) ...[
                if (widget.bottomWidget != null) ...[
                  const SizedBox(
                    height: 16,
                  ),
                  widget.bottomWidget!
                ],
                const SizedBox(
                  height: 16,
                ),
                Row(
                  children: [
                    if (_startButtonText.isNotEmpty) ...[
                      if (widget.onlyExpandConfirm ?? false) ...[
                        GTButtonV3(
                          text: _startButtonText,
                          buttonSize: GTButtonSizeV3.medium,
                          buttonType: GTButtonTypeV3.secondary,
                          paddingHorizontal: 24,
                          onPressed: () {
                            Navigator.pop(context);
                            widget.onCancelClick?.call();
                          },
                        )
                      ] else ...[
                        Expanded(
                            child: GTButtonV3(
                          text: _startButtonText,
                          buttonSize: GTButtonSizeV3.medium,
                          buttonType: GTButtonTypeV3.secondary,
                          onPressed: () {
                            Navigator.pop(context);
                            widget.onCancelClick?.call();
                          },
                        )),
                      ],
                      const SizedBox(
                        width: 8,
                      ),
                    ],
                    if (_endButtonText.isNotEmpty) ...[
                      Expanded(
                          child: GTButtonV3(
                        text: _endButtonText,
                        buttonSize: GTButtonSizeV3.medium,
                        onPressed: () {
                          Navigator.pop(context);
                          widget.onConfirmClick?.call();
                        },
                      )),
                    ],
                  ],
                ),
                SizedBox(
                  height: _isMiniApp ? 16 : 8,
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
